
module ESI
  class Config

    attr_reader :config
    
    def initialize(config_file)
      @config = YAML.load_file( config_file || "config/esi.yml" )
      @path_root = File.dirname( config_file || "config/esi.yml" )
      @config.symbolize_keys!
    end

    # access configuration values
    def [](key)
      @config[key]
    end

    def enable_esi_processor?( headers )
      !!(( @config[:enable_surrogate_control] and /ESI/.match(headers["Surrogate-Control"]) ) or 
      ( (@config[:match_content_type_text] || true) and /^text\//.match(headers["Content-Type"]) ))
    end
 
    # returns the cache object as given in the config/esi.yml
    # cache: key, or defaults to ruby as in uses this process
    # the options allowed are ruby and memcache
    def cache
			cache_type = @config[:cache]
			options = @config[cache_type.to_sym] || {}
      # always return the same cache object, per process
      $cache ||= case cache_type
      when 'ruby'
        ESI::RubyCache.new(options)
      when 'memcached'
        ESI::MemcachedCache.new(options)
      else
        raise "Unsupported cache"
      end
    end

    # return true/false depending on the value of 
    # invalidator: on/off
    # within in config/esi.yml
    def start_invalidator?
      @config[:invalidator]
    end

    def parser(router,cache)
      parser_to_use = @config[:parser] || 'stream'
      require "esi/#{parser_to_use}_parser"
      case parser_to_use
      when 'stream'
        ESI::StreamParser.new(router,cache)
      else
        raise "Unsupported parser"
      end
    end

  end    
end

